<?php
declare(strict_types=1);

namespace Modules\Web\Service;

use HiCommon\Model\ViewFinanceOrderPay;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\OrderCheckpointRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\ShopServerTypeRepository;
use HiCommon\Repository\AreasRepository;
use HiCommon\Repository\ShopModifyRepository;
use HiCommon\Repository\ShopMasterRepository;
use HiCommon\Repository\CheckpointServiceTypeRepository;
use HiCommon\Repository\ViewFinanceOrderPayRepository;


class ShopService extends BaseService
{

    /**
     *  获取门店下有过交易的所有用户
     *  hinq 2019 10 31
     *
     **/
    public function user_list( array $arr_search,$n_shop_id = 0 ){
        try{

            //查询商户信息
            $arr_field = ['id','cate'];
            $arr_shop = get_shop_by_id($n_shop_id,$arr_field);
            $n_shop_cate = intval($arr_shop['cate']);
            if(!in_array($n_shop_cate,[1,2])){
                return hello_error('店铺类型错误',[],'当前版本不包含道路救援商户');
            }

            $arr_search['sort_pay_price'] = $arr_search['act'] == 1 ? 'asc' : 'desc';
            $arr_search['sort_total'] = $arr_search['act_num'] == 1 ? 'asc' : 'desc';
            $arr_search['basic_wherein'] = [];

            //维修店才有
            if($n_shop_cate == 2){
                if(isset($arr_search['type'])){
                    if($arr_search['type'] == 1){
                        $arr_search['basic_wherein'] = ['order_type'=>['wxfw','wxby']];

                    }
                    elseif($arr_search['type'] == 2){
                        $arr_search['basic_wherein'] = ['order_type'=>['ptshp']];

                    }
                }
            }


            $result = ViewFinanceOrderPayRepository::get_user_list_for_shop($arr_search,$n_shop_id)->toArray() ;
            $data = list_page_data_for_api( $result); //将数据转换成接口的形式

            foreach ($data['data'] as &$value)
            {
                $value['pay_price'] = fee_to_money($value['pay_price']);
            }


//            //获取当前登录用户的信息
//            $user_info = web_user()->toArray();
//            $shop_id = get_web_shop_id();   //当前商户的门店id
//            //判断是否有搜索条件【用户昵称 或 手机号码】
//            $user_ids = [];
//            if( !empty( $arr_search['key_word'] ) ){
//                $arr_option['field'] = ['id'];
//                $userinfo = UsersRepository::get_all_to_search( (array) $arr_option , (array) $arr_search )->toArray();
//                foreach ( $userinfo as $item ){
//                    $user_ids['ids'][] = $item['id'];
//                }
//                $user_ids['key_word'] = true;
//            }
//            if( $user_info['type'] == 2 ){   //检测站
//                $where = ['shop_id'=>$shop_id,'pay_state'=>1];  //已支付
//                $arr_list = OrderCheckpointRepository::get_user_list( (array) $where , (array) $user_ids , (array) $arr_search )->toArray();
//            }else{   //维修点
//                $act = $arr_search['act'] == 1 ? 'asc' : 'desc';   //金额排序 1：小到大   2：大到小
//                if( $arr_search['type'] == 1 ){   //服务订单
//                    $where = ['shop_id'=>$shop_id,'pay_status'=>1];  //已支付
//                    $arr_list = OrderRepairstoreRepository::get_user_list( (array) $where , (string) $act ,(array) $user_ids)->toArray();
//                }else{     //普通订单
//                    $arr_where = ['shop_id'=>$shop_id ,'pay_status'=>1];   //已支付
//                    $arr_list = StoreOrderRepository::get_user_list( (array) $arr_where ,(string) $act, (array) $user_ids )->toArray();
//                }
//            }
//            $data = list_page_data_for_api( $arr_list ); //将数据转换成接口的形式
            return hello_success('ok',$data);
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取指定用户的详细信息
     *  hinq 2019 11 01
     *
     **/
    public function user_detail_for_shop( $n_user_id = 0 , $n_shop_id = 0){
        try {

            /*处理订单数据*/
            function format_data_for_order($res){
                $n_num = 0;
                $n_price_all = '0.00';
                if(!is_null($res)){
                    $arr_order_total = $res->toarray();
                    $n_num = $arr_order_total['total'];
                    $n_price_all = number_format_money($arr_order_total['pay_price']/100);
                }
                $data_res = [
                  'num' => $n_num,
                  'price_all' => $n_price_all,
                ];
                return $data_res;
            }

            if ($n_user_id <= 0) {
                return hello_error('用户id不能为空');
            }
            $arr_data = [];

            $where = ['id' => $n_user_id];
            $arr_option['field'] = ['id', 'username', 'head_img','nickname'];
            $result = UsersRepository::base_get_one($where,$arr_option);   //获取指定的用户信息
            if(is_null($result)){
                return hello_error('查询失败',[],'用户不存在');
            }

            /*用户信息*/
            $arr_user_info = $result->toarray();
            $arr_data['user'] = $arr_user_info;

            //商户信息
            $arr_option['field'] = ['id', 'cate'];
            $result = ShopRepository::base_find_one($n_shop_id,$arr_option);
            if(is_null($result)){
                return hello_error('查询失败',[],'商户不存在');
            }
            $arr_shop = $result->toarray();
            $n_shop_cate = $arr_shop['cate'];
            $arr_data['shop'] = $arr_shop;

            /*订单信息*/
            $result = ViewFinanceOrderPayRepository::get_user_order_total_for_shop($n_user_id,$n_shop_id);

            $result_geren = ViewFinanceOrderPayRepository::get_user_order_total_for_shop($n_user_id,$n_shop_id,['main_type'=>1]);
            $result_qiye = ViewFinanceOrderPayRepository::get_user_order_total_for_shop($n_user_id,$n_shop_id,['main_type'=>2]);


            $arr_order_type_list = ViewFinanceOrderPay::order_type_list();
            $data = [];
            foreach ($arr_order_type_list as $value)
            {
                $order_type = $value;
                $res = $result->where('order_type',$order_type)->first();
                $data[$order_type] = format_data_for_order($res);
            }

            if($n_shop_cate == 1){
                $arr_geren = format_data_for_order($result_geren->where('order_type','njyy')->first());
                $arr_qiye = format_data_for_order($result_qiye->where('order_type','njyy')->first());

                $arr_data['checkpoint'] = [
                  'geren'=>$arr_geren,
                  'qiye'=>$arr_qiye,
                ];

            }
            elseif ($n_shop_cate == 2){
                $arr_data['store'] = $data['ptshp'];
                $n_num = $data['wxfw']['num'] + $data['wxby']['num'];
                $n_price_all = $data['wxfw']['price_all'] + $data['wxby']['price_all'];
                $arr_data['repairstore'] = [
                  'num' => $n_num,
                  'price_all' => $n_price_all,
                ];
            }
            else{

            }
            $arr_data['order'] = $data;

            return  hello_success('成功',$arr_data);

//
//            $repairstore_id = get_web_shop_id();   //当前商户的门店id
//            $admin_info = web_user()->toArray();              //获取当前登录用户的账户信息
//
//            $map_store = ['shop_id' => $repairstore_id, 'user_id' => $n_user_id, 'pay_status' => 1];
//            if( empty( $user_info->first() ) ){   //这里的判断调用接口的时候放开
//                $data['user']=[];
//                $data['store']=[];
//                return hello_success('ok',[]);
//            }
//            if ($admin_info['type'] == 2) {   //检测站
//                //统计预约订单
//                $map_store = ['shop_id' => $repairstore_id, 'user_id' => $n_user_id, 'pay_state' => 1 , 'main_type'=>1];
//                $count_checkpoint_price = OrderCheckpointRepository::get_sum_by_where((array)$map_store, (string)'price');
//                $count_checkpoint_num = OrderCheckpointRepository::get_count_by_where((array)$map_store);
//                $data['checkpoint']['geren'] =[
//                    'num' => $count_checkpoint_num,
//                    'price_all' => $count_checkpoint_price,
//                ];
//                $map_store = ['shop_id' => $repairstore_id, 'user_id' => $n_user_id, 'pay_state' => 1 , 'main_type'=>2];
//
//                $count_checkpoint_price = OrderCheckpointRepository::get_sum_by_where((array)$map_store, (string)'price');
//                $count_checkpoint_num = OrderCheckpointRepository::get_count_by_where((array)$map_store);
//                $data['checkpoint']['qiye'] =[
//                    'num' => $count_checkpoint_num,
//                    'price_all' => $count_checkpoint_price,
//                ];
//            } else {   //维修店  【这里需要传参数 区别是普通订单还是服务订单】
//                //统计普通订单
//                $count_store_price = StoreOrderRepository::get_sum_by_where((array)$map_store, (string)'pay_amount');
//                $count_store_num = StoreOrderRepository::get_count_by_where((array)$map_store);
//                //统计服务订单
//                $map_store = ['shop_id' => $repairstore_id, 'user_id' => $n_user_id, 'pay_status' => 1];
//                $count_repairstore_price = OrderRepairstoreRepository::get_sum_by_where((array)$map_store, (string)'pay_price');
//                $count_repairstore_num = OrderRepairstoreRepository::get_count_by_where((array)$map_store);
//                $data['store'] =[   //商品订单统计
//                    'num' => $count_store_num,
//                    'price_all' => $count_store_price,
//                ];
//                $data['repairstore'] =[   //服务订单统计
//                    'num' => $count_repairstore_num,
//                    'price_all' => $count_repairstore_price,
//                ];
//            }
//            $data['user'] = $user_info;
//            return hello_success('ok',$data);
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取指定用户的基础信息
     *  hinq 2020 4 20
     **/
    public function user_info( string $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $where = ['username' => $nId];
            $arr_option['field'] = ['id','username','nickname','head_img'];
            $user_info = UsersRepository::get_one_by_where((array)$where, (array)$arr_option);   //获取指定的用户信息
            if( empty( $user_info->first() ) ){
                return hello_error('参数错误');
            }
            $head_img = $user_info['head_img']['full_src'];
            unset( $user_info['head_img'] );
            $user_info['image'] = oss_full_url( $head_img );
            return hello_success( 'ok' , $user_info );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }

    /**
     *  获取指定用户在当前门店下参与的活动列表
     *  hinq 2019 11 01
     *
     **/
    public function activity_list( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }

            $repairstore_id = get_web_shop_id();   //当前商户的门店id
//            $repairstore_id = 4;   //当前商户的门店id
            //获取指定用户的所有的活动订单
            //               指定用户  当前门店 并且是活动订单
            $arr_option['where'] = ['shop_id'=>$repairstore_id , 'user_id'=>$nId,'order_type'=>2];
            $arr_option['field'] = ['id','user_id','activity_id','created_at'];
            $arr_option['with'] = ['activity'];
            $arr_list = StoreOrderRepository::get_list( (array) $arr_option )->toArray();
            $data = list_page_data_for_api( $arr_list ); //将数据转换成接口的形式
            foreach ( $data['data'] as $key => &$value ){
                $value['activity']['start_time'] = date('Y-m-d',$value['activity']['start_time']);
                $value['activity']['over_time'] = date('Y-m-d',$value['activity']['over_time']);
            }
            return hello_success('ok',$data);
        }catch(\Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取指定用户在当前门店下所有的服务订单
     *  hinq 2019 11 01
     *
     **/
    public function repairstore_order_list( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $repairstore_id = get_web_shop_id();   //当前商户的门店id
            $repairstore_id = 1;   //当前商户的门店id
            $arr_option['where'] = ['shop_id'=> $repairstore_id ,'user_id'=>$nId,'pay_status'=>1];
            $arr_option['field'] = ['id','order_number','repairstore_goods_id','created_at'];
            $arr_option['with'] = ['to_goods','to_goods.pic'];
            $arr_list = OrderRepairstoreRepository::get_list( (array) $arr_option )->toArray();

            $data = list_page_data_for_api( $arr_list ); //将数据转换成接口的形式
            foreach ( $data['data'] as $key => &$value ){
                $value['to_goods']['pic'] = $value['to_goods']['pic'][0]['picurl'];
            }

//            $num = 0;
//            $price_all = 0;
//            foreach( $data['data'] as $key => &$value ){
//                $value['to_goods']['img'] = $value['to_goods']['pic'][0]['picurl']['full_src'];   //商品的主图
//                unset( $value['to_goods']['pic'] );  //释放多余的信息
//                $num++;
//                $price_all = $price_all+$value['to_goods']['price'];
//            }
//            $data['count_order'] = [
//                'num'=>$num,
//                'price_all' => $price_all
//            ];
            return hello_success('ok',$data);
        }catch(\Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取指定用户在当前门店下所有的普通（含活动）订单
     *  hinq 2019 11 01
     *
     **/
    public function store_order_list( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $repairstore_id = get_web_shop_id();   //当前商户的门店id
            $repairstore_id = 4;   //当前商户的门店id
            $arr_option['where'] = ['shop_id'=> $repairstore_id ,'user_id'=>$nId,'pay_status'=>2];
            $arr_option['field'] = ['id','order_no','created_at','goods_num','order_amount'];
            $arr_option['with'] = ['getOrderGoods'];
            $arr_list = StoreOrderRepository::get_list( (array) $arr_option)->toArray();
            $data = list_page_data_for_api( $arr_list ); //将数据转换成接口的形式
//            $num = 0;
//            $price_all = 0;
//            foreach ( $data['data'] as $item) {
//                foreach ( $item['get_order_goods'] as $value ) {
//                    $num++;
//                    $price_all = $price_all + $value['goods_product']['goods_info']['price'];
//                }
//            }
//            $data['count_order'] = [
//                'num'=>$num,
//                'price_all'=>$price_all
//            ];
            return hello_success('ok',$data);
        }catch(\Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取指定用户在当前门店下所有的预约订单
     *  hinq 2019 11 01
     *  [该功能未完善]
     **/
    public function checkpoint_order_list( array $arr_input ){
        try{
            if( empty( $arr_input['user_id'] ) ){
                return hello_error('参数错误');
            }
            $nId  = $arr_input['user_id'];
            $main_type = empty($arr_input['main_type'])? 1 : $arr_input['main_type']; //订单类型  1：个人  2：企业
            $repairstore_id = get_web_shop_id();   //当前商户的门店id
            $repairstore_id = 3;   //当前商户的门店id
            $arr_option['where'] = ['shop_id'=> $repairstore_id ,'user_id'=>$nId,'pay_state'=>2,'main_type'=>$main_type];
            $arr_option['field'] = ['id','order_sn','created_at','price','shop_id','user_id'];
            $arr_option['with'] = ['shop'];
            $arr_list = OrderCheckpointRepository::get_list( (array) $arr_option)->toArray();
            $data = list_page_data_for_api( $arr_list ); //将数据转换成接口的形式
//            $num = 0;
//            $price_all = 0;
//            foreach ( $data['data'] as $item ){
//                $num++;
//                $price_all = $price_all +  $item['price'] ;
//            }
//            $data['count_order'] = [
//                'num'=>$num,
//                'num'=>$num,
//                'price_all' => $price_all
//            ];
            return hello_success('ok',$data);
        }catch(\Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取指定门店的详细信息
     *  hinq 2019 11 04
     *
     **/
    public function get_shop_detail(){
        $where = ['id'=>web_user()->toarray()['shop_id'],'status'=>1];
        $arr_option['with'] = ['shop_img'];
        $arr_info = ShopRepository::get_one_by_where( (array) $where , (array) $arr_option );
        $repairstore_id = get_web_shop_id();   //当前商户的门店id

        if( $arr_info['type'] ){  //检测站
            $service_types = '';
            //获取检测站的服务类型
            $sever_option['where'] = ['checkpoint_id'=>$repairstore_id,'status'=>1];
            $sever_option['field'] = ['id','title'];
            $typrs = CheckpointServiceTypeRepository::get_all( (array) $sever_option );

            if( empty( $typrs->first() ) ){
                $arr_types = '';
            }else{
                foreach ( $typrs->toArray() as $key => $vo ){
                    $service_types .= ',' . $vo['title'];
                }
                $arr_types = trim($service_types , ',');
            }
            $arr_info['Checkpoint_types'] = $arr_types;
            $arr_info['types'] = [];   //兼容安卓端
        }else{
            //获取服务类型的名称
            $ids = explode(',',$arr_info['types']);
            $arr_option2['field'] = ['name','id'];
            $arr_types = ShopServerTypeRepository::get_whereIn_list( (array) $ids, (array) $arr_option2 )->toArray();

            //获取门店的技师数量
            $count_master = ShopMasterRepository::get_count_by_where( (array) ['shop_id'=>$repairstore_id]);
            $arr_info['count_master'] = $count_master;
            $arr_info['types'] = $arr_types;
        }
        $map['id'] = $arr_info['province'];
        $province = AreasRepository::get_city_infor( (array) $map )->toArray();
        $map['id'] = $arr_info['city'];
        $city = AreasRepository::get_city_infor((array) $map )->toArray();
        $map['id'] = $arr_info['area'];
        $area = AreasRepository::get_city_infor( (array) $map )->toArray();
        $arr_info['province_name'] = $province['name'];
        $arr_info['city_name'] = $city['name'];
        $arr_info['area_name'] = $area['name'];

        //查看该门店是否有申请变更信息
        $arr_modify = ShopModifyRepository::get_one_by_where( (array) ['shop_id' =>$repairstore_id]);
        $modify = null;
        if( !empty( $arr_modify->first() ) ){
            $modify['status'] = $arr_modify->toArray()['status'];
            $modify['remark'] = $arr_modify->toArray()['remark'];
        }
        $arr_info['modify'] = $modify;

        return hello_success('ok',$arr_info);
    }

    /**
     *  获取门店服务类型变更信息时获取服务类型
     *  hinq 2019 11 04
     *
     ***/
    public function server_type_list(){
        $arr_option['where'] = ['status'=>1,'type'=>1,'pid'=>0];
        $arr_option['field'] = ['id','name','pid'];
        $arr_option['with'] = ['shop_server_type'];
        $arr_list = ShopServerTypeRepository::get_all( (array) $arr_option )->toArray();
        return hello_success('ok',$arr_list);
    }

    /**
     *  编辑维修店、检测站基本信息
     *  hinq 2019 11 19
     *
     **/
    public function shop_update( array $arr_input ){

        try{
            $info = web_user();

            if( $info['type'] == 3 ){  //维修店
                if( empty( $arr_input['name'] ) ){
                    return hello_error('门店名称不能为空');
                }
            }
            if( empty( $arr_input['phone_shop'] ) ){
                return hello_error('门店电话不能为空');
            }
            if( !preg_match("/^1[3456789]\d{9}$/", $arr_input['phone_shop'] ) ){
                return hello_error('门店电话格式不正确');
            }

//            if( !preg_match("/^\d{3,4}-\d{7,8}$/",$arr_input['phone_boss'])){
//                return ['state'=> 1,'msg'=>'门店电话格式不正确','data'=>[],'error'=>''];
//            }
            if( empty( $arr_input['logo'] ) ){
                return hello_error('头像不能为空');
            }
            $repairstore_id = get_web_shop_id();   //当前商户的门店id
            $data['name'] = $arr_input['name'];   //门店名称
            if( $info['type'] == 3 ) {  //维修店
                    if (!empty($arr_input['types'])) {
                    $data['types'] = $arr_input['types'];   //服务类型
                }
            }
            $data['phone_shop'] = $arr_input['phone_shop'];   //门店电话
            $data['logo'] = $arr_input['logo'];   //图像地址
            $data['id'] = $repairstore_id;

            $res = ShopRepository::edit_one( (array) $data );
            if( empty( $res) ){
                return hello_error('编辑失败');
            }

            //如果是检测站修改信息
            if( $info['type'] == 2 ){  //检测站
                //删除检测站之前的服务类型
                CheckpointServiceTypeRepository::delete_where( (array) ['checkpoint_id'=>$repairstore_id]);
                if( !empty($arr_input['types']) ){
                    $temp['checkpoint_id'] = $repairstore_id;
                    $service_type = explode(',',$arr_input['types']);
                    foreach ( $service_type as $key => $vo ){
                        $temp['title'] = $vo;
                        CheckpointServiceTypeRepository::add_one( (array) $temp);
                    }
                }
            }
            return hello_success('ok');
        }catch(\Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  通过用户的id获取用户的rong_cloud_id
     *  hinq 2020 4 22
     *
     ***/
    public function get_rong_cloud_id( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $arr_option['field'] = ['id','username','nickname','head_img'];
            $arr_info = UsersRepository::get_one( (int) $nId , (array) $arr_option );

            if(  empty( $arr_info ) ){
                return hello_success('ok', []);
            }
            $arr_info['image'] = oss_full_url($arr_info['head_img']['full_src']);
            unset( $arr_info['head_img'] );
            return hello_success('ok', $arr_info);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }



}